import styles from "./index.module.scss"
import { useSelector, } from "react-redux"
import { Row, Col, Image, Anchor, Avatar, Input, Button, Form, ConfigProvider, theme, message } from "antd"
import { CommentOutlined, EyeOutlined, HeartFilled } from "@ant-design/icons"
import { useState, useEffect } from "react"
import { Get_One, addview } from '@/apis/foods'
import dayjs from "dayjs"
import { useParams } from "react-router-dom"
import { toCollect, cancelCollect, getone } from "@/apis/collect"
import { Local } from "@/utils/local"
import { addidsucss, getdiscuss } from "@/apis/discuss"
let timer: any = null
const base_url = import.meta.env.VITE_APP_URL
interface DETAIL {
    Cover_img: string,
    catalog?: [],
    publish_time: number,
    review: number,
    rich_text: string,
    texttual: string,
    title: string,
    type: string,
    user_id: string,
    _id: string
}
const getEnum = (data: any[]) => {
    const temp: object[] = []
    data.forEach((item: any, index) => {
        if (item.type === "header1") {
            const nodes: any = {
                key: item.children[0].text,
                href: '#' + item.children[0].text,
                title: item.children[0].text,
                children: []
            }
            for (let i = index + 1; i < data.length; i++) {
                if (data[i].type === "header1") {
                    break
                } else {
                    nodes.children.push({
                        key: data[i].children[0].text,
                        href: '#' + data[i].children[0].text,
                        title: data[i].children[0].text,
                    })
                }
            }
            temp.push({ ...nodes })
        }
    })
    return temp
}
// getone
const Detaile = () => {
    const userid = Local.get_info()._id
    const thems = useSelector((state: any) => state.Appstore.theme)
    const [isactive, setisactive] = useState(false)
    const [windowWidth, setWindowWidth] = useState(window.innerWidth)
    const [discussList, setdiscussList] = useState<[]>([])
    const [detail, setdetail] = useState<DETAIL>({
        Cover_img: '',
        publish_time: 0,
        review: 0,
        rich_text: '',
        texttual: '',
        title: '',
        type: '',
        user_id: '',
        _id: ''
    })
    const [Enum, setEnum] = useState<any>([])
    const [form] = Form.useForm()
    const params = useParams()
    const getdiscusslist = async (id: string) => {
        const res = await getdiscuss(id)
        setdiscussList(res.data)
    }
    const InputChange = (e: any) => {
        if (e.target.value.length > 40) {
            form.setFieldsValue({ speak: e.target.value.slice(0, 50) })
        }
    }
    const onFinish = async (e: any) => {
        const user_id = Local.get_info()._id
        if (!user_id) {
            message.error("请登录")
            return
        }
        const result = await addidsucss({ user_id, content: e.speak, food_id: detail._id })
        if (result.status === 200) {
            message.success("发布成功")
            getdiscusslist(detail._id)
            form.resetFields()
        }
    }
    useEffect(() => {
        Get_One(params.id as string).then(async (res) => {
            setEnum([...getEnum(res.data.catalog)])
            setdetail({ ...res.data, rich_text: `${res.data.rich_text.toString()}` })
            const result = await getone({ user_id: userid, food_id: res.data._id })
            if (result.status === 200) {
                setisactive(true)
            }
            getdiscusslist(res.data._id)
            addview(res.data._id)
        })
        const handleResize = () => setWindowWidth(window.innerWidth);
        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, [])
    const RenderColContent = () => {
        if (windowWidth < 768) {
            return <ConfigProvider
                theme={{
                    algorithm: thems ? theme.defaultAlgorithm : theme.darkAlgorithm,
                    components: {
                        Switch: {
                            colorPrimary: "orange",
                            colorPrimaryHover: "orange"
                        }
                    },
                }}
            >
                {
                    detail.publish_time && <Col xs={24} sm={18} md={24} lg={24}>
                        <div style={{ width: "100%", display: "flex", flexDirection: "column", alignItems: "center" }}>
                            <div style={{ width: "100%", display: "flex", background: thems ? 'rgba(255,255,255,0.7)' : "rgba(0,0,0,0.7)" }}>
                                <div style={{ width: "80%", boxSizing: "border-box", padding: "5px", cursor: 'default', pointerEvents: 'none' }} id="articleContainer" className={styles.bodyimg} dangerouslySetInnerHTML={{ __html: detail.rich_text }} ></div>


                                <div style={{ width: "20%" }}> <Anchor
                                    style={{ borderLeft: '1px solid orange', }}
                                    items={Enum}
                                /></div>
                            </div>

                            {
                                discussList.length !== 0 && discussList.map((item: any, index: number) => {
                                    const times = dayjs(item.publish_time).format('YYYY-MM-DD HH:mm')
                                    return <div key={index} style={{ width: "99%", marginTop: "10px", background: thems ? 'rgba(255,255,255,0.7)' : "rgba(0,0,0,0.7)", display: "flex", alignItems: "center", padding: "5px", boxSizing: 'border-box' }}>
                                        <div style={{ display: 'flex' }}>
                                            <Avatar size={"large"} src={base_url + item.user.avatar}></Avatar>
                                            <div style={{ marginLeft: "10px" }}>{item.user.username}</div>
                                        </div>
                                        <div style={{ marginLeft: "10px" }}>
                                            <p>{item.content}</p>
                                            <p>{times}</p>
                                        </div>
                                    </div>
                                })
                            }

                            <div style={{ width: "80%", padding: "10px", marginTop: "10px", background: thems ? 'rgba(255,255,255,0.7)' : "rgba(0,0,0,0.7)" }}>
                                <Form form={form}
                                    name="basic"
                                    onFinish={onFinish}>
                                    <Form.Item name="speak"

                                        rules={[{ required: true, message: '输入至少三个字', min: 3 }]}
                                    >
                                        <Input.TextArea onChange={InputChange} count={

                                            {
                                                max: 50,
                                                strategy: () => 1,

                                                show: ((args: { value: string; count: number; maxLength?: number }) => {

                                                    return <p>{args.value.length}/{args.maxLength}</p>
                                                }),
                                            }
                                        }></Input.TextArea>
                                    </Form.Item>
                                    <Form.Item>
                                        <div style={{ textAlign: 'center' }}>

                                            <Button htmlType="submit">发布</Button>

                                        </div>
                                    </Form.Item>
                                </Form>


                            </div>

                        </div>
                    </Col >
                }
            </ConfigProvider>
        } else {
            return (
                <ConfigProvider

                    theme={{
                        algorithm: thems ? theme.defaultAlgorithm : theme.darkAlgorithm,
                        components: {
                            Switch: {
                                colorPrimary: "orange",
                                colorPrimaryHover: "orange"
                            }
                        },
                    }}
                >
                    <Col xs={24} sm={18} md={24} lg={24}>

                        <div style={{ width: "100%", display: "flex", flexDirection: 'column', alignItems: 'center' }}>
                            <div style={{ width: "60%", display: "flex", background: thems ? 'rgba(255,255,255,0.7)' : "rgba(0,0,0,0.7)", }}>
                                <div style={{ width: "80%" }}>
                                    <div id="articleContainer" style={{
                                        boxSizing: "border-box", padding: "10px",
                                        pointerEvents: 'none'
                                    }} className={styles.bodyimg} contentEditable={false} dangerouslySetInnerHTML={{ __html: detail.rich_text }}></div>
                                </div>
                                <div style={{ width: "20%" }}> <Anchor
                                    style={{ borderLeft: '1px solid orange', }}
                                    items={Enum}
                                /></div>
                            </div>

                            {
                                discussList.length !== 0 && discussList.map((item: any, index: number) => {
                                    const times = dayjs(item.publish_time).format('YYYY-MM-DD HH:mm')
                                    return <div key={index} style={{ width: "60%", marginTop: "5px", background: thems ? 'rgba(255,255,255,0.7)' : "rgba(0,0,0,0.7)", display: "flex", alignItems: "center", padding: "5px", boxSizing: 'border-box' }}>
                                        <div style={{ display: 'flex' }}>
                                            <Avatar size={"large"} src={base_url + item.user.avatar}></Avatar>
                                            <div style={{ marginLeft: "10px" }}>{item.user.username}</div>
                                        </div>
                                        <div style={{ marginLeft: "10px", }}>
                                            <p>{item.content}</p>
                                            <p>{times}</p>
                                        </div>
                                    </div>
                                })
                            }


                            <div style={{ width: "50%", padding: "10px", marginTop: "10px", background: thems ? 'rgba(255,255,255,0.7)' : "rgba(0,0,0,0.7)" }}>
                                <Form form={form}
                                    name="basic"
                                    onFinish={onFinish}
                                >
                                    <Form.Item name="speak"
                                        rules={[{ required: true, message: '输入至少三个字', min: 3 }]}
                                    >
                                        <Input.TextArea onChange={InputChange} count={

                                            {
                                                max: 50,
                                                strategy: () => 1,

                                                show: ((args: { value: string; count: number; maxLength?: number }) => {

                                                    return <p>{args.value.length}/{args.maxLength}</p>
                                                }),
                                            }
                                        }></Input.TextArea>
                                    </Form.Item>
                                    <Form.Item>
                                        <div style={{ textAlign: 'center' }}>

                                            <Button htmlType="submit">发布</Button>

                                        </div>
                                    </Form.Item>
                                </Form>


                            </div>
                        </div>


                    </Col>
                </ConfigProvider>
            );
        }
    };
    const collect = async () => {
        const user_id = Local.get_info()._id

        clearTimeout(timer)

        timer = setTimeout(async () => {
            if (!isactive) {
                setisactive(true)

                await toCollect({ user_id, food_id: detail._id })

            } else {
                setisactive(false)

                await cancelCollect({ user_id, food_id: detail._id })

            }
        }, 200);



    }
    return (
        <div>
            {
                detail.publish_time ? <div className={thems ? styles.R_light : styles.R_dark} >
                    <div style={{ width: "100%", height: "100%" }}>

                        <Row justify={"center"} >
                            <Col xs={0} sm={0} md={24} lg={24} >
                                <div style={{ width: '100%', display: "flex", position: "relative", justifyContent: "center" }}>
                                    <Image
                                        preview={{
                                            mask: ""
                                        }}
                                        width={"60%"} style={{ maxHeight: "300px" }} src={base_url + detail.Cover_img}></Image>
                                    <div style={{ display: "flex", width: "60%", boxSizing: "border-box", position: 'absolute', bottom: '0', padding: "10px", background: "rgba(0,0,0,0.6)", color: "rgba(255,255,255,0.7)" }}>
                                        <p>{detail.title}</p>
                                        <p style={{ margin: "0 20px" }}>{dayjs(detail.publish_time).format('YYYY-MM-DD')}</p>
                                        <p style={{ margin: "0 10px" }}> <EyeOutlined />
                                            {detail.review}</p>
                                        <p style={{ margin: "0 10px" }}> <CommentOutlined />
                                            {discussList.length}</p>

                                        <p onClick={collect} style={{ margin: "0 20px" }} className={styles.love}><HeartFilled style={{ color: isactive ? 'red' : '', fontSize: "18px" }} /></p>

                                    </div>
                                </div>
                            </Col>
                            <Col xs={24} sm={18} md={0} lg={0}>
                                <div style={{ width: '100%', display: "flex", justifyContent: "center" }}>
                                    <Image
                                        preview={{
                                            mask: ""
                                        }}
                                        width={"100%"} style={{ maxHeight: "300px" }} src={base_url + detail.Cover_img}></Image>
                                    <div style={{ display: "flex", alignContent: "center", width: "100%", boxSizing: "border-box", position: 'absolute', bottom: '0', padding: "10px", background: "rgba(0,0,0,0.6)", color: "rgba(255,255,255,0.7)" }}>
                                        <p>{detail.title}</p>
                                        <p style={{ margin: "0 20px" }}>{dayjs(detail.publish_time).format('YYYY-MM-DD')}</p>
                                        <p style={{ margin: "0 10px" }}> <EyeOutlined />
                                            {detail.review}</p>
                                        <p > <CommentOutlined />
                                            {discussList.length}</p>

                                        <p onClick={collect} style={{ margin: "0 20px" }} className={styles.love}><HeartFilled style={{ color: isactive ? 'red' : '', fontSize: "18px", }} /></p>

                                    </div>
                                </div>
                            </Col>
                        </Row>
                        <Row justify={"center"}>
                            <RenderColContent></RenderColContent>
                        </Row>
                    </div>

                </div> : <div style={{ width: '100vw', textAlign: "center" }}>没有内容可以展示</div>
            }

        </div>

    )
}

export default Detaile